package com.imooc.controller;

import com.imooc.pojo.IMoocJSONResult;
import com.imooc.pojo.Logan;
import com.imooc.service.LoganService;
import com.imooc.utils.FileUtil;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.LoganFileReader;
import com.imooc.utils.LoganParser;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/upload")
public class UploadContoller {

    @Autowired
    private LoganService loganService;
    private String Key16 = "0123456789012345";
    private String Iv16 = "0123456789012345";

    @RequestMapping("file")
    public String Upload() {
        return "/thymeleaf/upload";
    }

    @RequestMapping("multifile")
    public String Uploads() {
        return "/thymeleaf/multifile";
    }

    @PostMapping("uploadfile")
    @ResponseBody
    public IMoocJSONResult UploadFile(@RequestParam("fileName") MultipartFile file) {
        if (file.isEmpty()) {
            return IMoocJSONResult.errorMsg("file is  Empty");
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

//        File encFile = new File("F:/test/lblb"); //加密文件
        File encFilelb = new File("F:/test/lb"); //加密文件
        String path = "F:/test";
        File dest = new File(path + "/" + fileName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
//        if (!encFile.getParentFile().exists()) { //判断文件父目录是否存在
//            encFile.getParentFile().mkdir();
//        }
        try {
            file.transferTo(dest); //保存文件
            FileInputStream inputStream = new FileInputStream(dest);
            OutputStream outputStream = new FileOutputStream(encFilelb);
            new LoganParser(Key16.getBytes(), Iv16.getBytes()).parse(inputStream, outputStream);
            outputStream.close();
            return IMoocJSONResult.ok();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return IMoocJSONResult.errorMsg("Exception");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return IMoocJSONResult.errorMsg("Exception");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return IMoocJSONResult.errorMsg("Exception");
        }
    }

    /**
     * 实现多文件上传
     * <p>
     * public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files)
     */
    @PostMapping("/multiFileUpload")
    @ResponseBody
    public IMoocJSONResult multiFileUpload(HttpServletRequest request) {
        System.out.println("-->multiFileUpload");
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("filename");
        String name = request.getParameter("name");
        if (files.isEmpty()) {
            return IMoocJSONResult.errorMsg("文件为空！");
        }

        String path = "F:/test";//存储路径

        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println("name:" + name + "---" + fileName + "-->" + size);

            if (file.isEmpty()) {
                return IMoocJSONResult.errorMsg("文件为空！");
            } else {
                File dest = new File(path + "/" + fileName);
                if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                    File encFilelb = new File("F:/test/lbAS"); //解密后的文件
                    FileInputStream inputStream = new FileInputStream(dest);
                    OutputStream outputStream = new FileOutputStream(encFilelb);
                    new LoganParser(Key16.getBytes(), Iv16.getBytes()).parseWithZip(inputStream, outputStream);
                    outputStream.close();
                    inputStream.close();
                    List<String> stringList = LoganFileReader.readFile02("F:/test/lbAS");
                    System.out.println(stringList);
                    List<Logan> loganList = JsonUtils.jsonToList(stringList.toString(), Logan.class);
                    loganService.insertIntoLogan(loganList);
                    System.out.println(stringList);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return IMoocJSONResult.errorMsg("解析失败！");
                }
            }
        }
        return IMoocJSONResult.ok();
    }

    /**
     * 实现多文件上传
     * <p>
     * public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files)
     */
    @PostMapping("multifileUploadFile")
    @ResponseBody
    public IMoocJSONResult multifileUploadFile(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("filename");
        String name = request.getParameter("name");
        String client = request.getParameter("client");
        if (files.isEmpty()) {
            System.out.println("文件为空");
            return IMoocJSONResult.errorMsg("文件为空！");
        }
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println("name:" + name + "---client:" + client + "---" + fileName + "-->" + size);

            if (file.isEmpty()) {
                System.out.println("文件为空");
                return IMoocJSONResult.errorMsg("文件为空！");
            } else {
                File dest = new File("F:/test/catch/" + fileName);
                if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                    InputStream inputStream = new FileInputStream(dest);
                    File outFile = new File("F:/test/catchOut/" + fileName);
                    if (!outFile.getParentFile().exists()) { //判断文件父目录是否存在
                        outFile.getParentFile().mkdir();
                    }
                    OutputStream outputStream = new FileOutputStream(outFile);
                    new LoganParser(Key16.getBytes(), Iv16.getBytes()).parseWithZip(inputStream, outputStream);
                    outputStream.close();
                    inputStream.close();

                    List<String> stringList = LoganFileReader.readFile02(outFile);
                    System.out.println("解析结果;\n" + stringList);
                    System.out.println("插入数据库;...");
                    List<Logan> loganList = JsonUtils.jsonToList(stringList.toString(), Logan.class);
                    long status = loganService.insertIntoLogan(loganList);
                    if (status != 0) {
                        return IMoocJSONResult.ok("解析成功，插入成功！" + status);
                    } else {
                        return IMoocJSONResult.ok("解析成功，插入失败！" + status);
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return IMoocJSONResult.errorMsg("解析失败！");
                }
            }
        }
        return IMoocJSONResult.ok("请求成功！");
    }

    /**
     * 实现多文件上传
     * <p>
     * public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files)
     */
    @PostMapping("multiFileUploadNoAnalysis")
    @ResponseBody
    public IMoocJSONResult multiFileUploadNoAnalysis(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("filename");
        String name = request.getParameter("name");
        String client = request.getParameter("client");
        StringBuilder result = new StringBuilder();
        if (files.isEmpty()) {
            System.out.println("文件为空");
            return IMoocJSONResult.errorMsg("文件为空！");
        }
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println("name:" + name + "---client:" + client + "---" + fileName + "-->" + size);
            result.append(name);
            if (file.isEmpty()) {
                result.append(":文件为空");
                System.out.println("文件为空");
            } else {
                boolean success = FileUtil.parseImmediately(file, "F:/test/catch/", fileName);
                result.append(":" + success);
            }
        }
        return IMoocJSONResult.ok(result);
    }
}
